#include <qdebug.h>
#include "AsyncScriptExecutorPrivate.h"
#include "SDKCorePrivate.h"

AsyncScriptExecutorPrivate::AsyncScriptExecutorPrivate(QObject* parent):
QThread(parent)
{
}

AsyncScriptExecutorPrivate::~AsyncScriptExecutorPrivate()
{
}

void AsyncScriptExecutorPrivate::setFinishedCallback(const std::function<void()>& cb)
{
    callback = cb;
}

void AsyncScriptExecutorPrivate::execute(const QString& script)
{
	stop();
	running_ = true;

	auto lines = script.split("\n");
	foreach(auto line,lines)
		if(!line.isEmpty() && !line.startsWith('#'))
			command << line;

	start();
}
	
void AsyncScriptExecutorPrivate::stop()
{
	if(isRunning())
	{
		running_ = false;
		quit();
	    wait();
	}
}

int AsyncScriptExecutorPrivate::getSleepTime(const QString& script)
{
	auto prefix = QString("(SDKCore)(ScriptExecutor)(sleepInThread)(");
	if(!script.startsWith(prefix))
		return 0;

	return script.mid(prefix.size(),script.size()-prefix.size()-1).toInt();
}
	
bool AsyncScriptExecutorPrivate::running()const
{
	return running_;
}

void AsyncScriptExecutorPrivate::run()
{
#define SLEEP_TIME 12
	foreach(auto item,command)
	{
		if(!running_) 
			break;

		int sleep = getSleepTime(item);
		if(sleep == 0)
			emit asyncCallScript(item);

		while(true)
		{
			msleep(SLEEP_TIME);
			if(sleep > 0)
			    sleep -= SLEEP_TIME;
			else
				break;
		}
	}

	if(callback)
		callback();
}